package com.wnhz.work.yz.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.AddPlanThemeBean;
import com.wnhz.work.yz.bean.PlanDetailBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddPlanActivity extends BaseActivity implements View.OnClickListener {

    private TextView mPlan_type;
    private TextView mPlan_start_time;
    private TextView mPlan_end_time;
    private TextView mPlan_message;
    private TextView plan_complete;
    private TextView plan_termination;
    private TextView plan_delete;

    private LinearLayout mLl_end_time;
    private EditText mPlan_info;
    private EditText mPlan_theme;
    private LinearLayout mAdd_product;
    // End Of Content View Elements
    private RecyclerView message_recycler;
    private List<AddPlanThemeBean.ProjectEntity> messageData = new ArrayList<>();
    private List<String> messages = new ArrayList<>();
    private LinearLayout ll_buttom, ll_delete;

    private void bindViews() {
        plan_termination = (TextView) findViewById(R.id.plan_termination);
        plan_complete = (TextView) findViewById(R.id.plan_complete);
        plan_delete = (TextView) findViewById(R.id.plan_delete);

        ll_buttom = (LinearLayout) findViewById(R.id.ll_buttom);
        ll_delete = (LinearLayout) findViewById(R.id.ll_delete);
        mPlan_type = (TextView) findViewById(R.id.plan_type);
        mPlan_info = (EditText) findViewById(R.id.plan_info);
        mPlan_start_time = (TextView) findViewById(R.id.plan_start_time);
        mLl_end_time = (LinearLayout) findViewById(R.id.ll_end_time);
        mPlan_end_time = (TextView) findViewById(R.id.plan_end_time);
        mPlan_theme = (EditText) findViewById(R.id.plan_theme);
        mPlan_message = (TextView) findViewById(R.id.plan_message);
        mAdd_product = (LinearLayout) findViewById(R.id.add_product);
        message_recycler = (RecyclerView) findViewById(R.id.message_recycler);
        message_recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new MyMeaagerAdapter(this, messageData);
        message_recycler.setAdapter(adapter);
        if ("0".equals(status) || "1".equals(status)) {
            showDialog();
            uploadDetail();
            ll_buttom.setVisibility(View.VISIBLE);
            plan_complete.setOnClickListener(this);
            plan_termination.setOnClickListener(this);
        } else if ("2".equals(status) || "3".equals(status) || "4".equals(status)) {
            showDialog();
            uploadDetail();
            ll_delete.setVisibility(View.VISIBLE);
            plan_delete.setOnClickListener(this);
            mPlan_message.setOnClickListener(this);
            mPlan_theme.setEnabled(false);
            mPlan_info.setEnabled(false);
        }


    }

    private void uploadDetail() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("planid", planid + "");
        XUtil.Post(Url.PLAN_PLANDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("---", result);
                Gson gson = new Gson();
                PlanDetailBean bean = gson.fromJson(result, PlanDetailBean.class);
                PlanDetailBean.InfoEntity info = bean.getInfo();
                if ("0".equals(info.getType())) {
                    mPlan_type.setText("周计划");
                    mLl_end_time.setVisibility(View.GONE);
                } else if ("1".equals(info.getType())) {
                    mPlan_type.setText("月计划");
                    mLl_end_time.setVisibility(View.GONE);
                } else if ("2".equals(info.getType())) {
                    mPlan_type.setText("自定义");
                    mLl_end_time.setVisibility(View.VISIBLE);
                    mPlan_end_time.setText(info.getEnd_time());
                }
                mPlan_info.setText(info.getTitle() + "");
                mPlan_start_time.setText(info.getStart_time());
                mPlan_theme.setText(info.getProject().get(0).getTitle());
                messages = info.getProject().get(0).getContent();
                messageData.clear();
                for (int i = 1; i < info.getProject().size(); i++) {
                    AddPlanThemeBean.ProjectEntity p = new AddPlanThemeBean.ProjectEntity();
                    p.setContent(info.getProject().get(i).getContent());
                    p.setTitle(info.getProject().get(i).getTitle());
                    messageData.add(p);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private MyMeaagerAdapter adapter;

    class MyMeaagerAdapter extends BaseRVAdapter {
        private List<AddPlanThemeBean.ProjectEntity> messageData;

        /**
         * 构造器
         *
         * @param context 上下文
         * @param list    数据集合
         */
        public MyMeaagerAdapter(Context context, @NonNull List list) {
            super(context, list);
            messageData = list;
        }

        @Override
        public int getLayoutId(int viewType) {
            return R.layout.add_plan_item_theme;
        }


        @Override
        public void onBind(BaseViewHolder holder, final int position) {
            holder.setTextView(R.id.more_tv_title, "新建主题" + (position + 1) + "：");
            holder.setTextView(R.id.more_title, messageData.get(position).getTitle());
            EditText more_title = holder.getView(R.id.more_title);
            if ("2".equals(status) || "3".equals(status) || "4".equals(status)) {
                more_title.setFocusable(false);
                more_title.setEnabled(false);
            } else {
                more_title.setFocusable(true);
                more_title.setEnabled(true);

            }
            more_title.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    messageData.get(position).setTitle(s.toString());
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

            holder.getTextView(R.id.more_theme).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(AddPlanActivity.this, MorePlanMessageActivity.class);
                    ArrayList<String> message = (ArrayList<String>) messageData.get(position).getContent();
                    intent.putExtra("moreData", message);
                    intent.putExtra("position", position);
                    intent.putExtra("status", status);
                    startActivityForResult(intent, PLANMESSAGEITEM);
                }
            });


        }

    }


    private List<String> types = new ArrayList<>();
    private String status = "";
    private String planid = "";
    private int isisis = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_plan);

        planid = getIntent().getStringExtra("planid");
        status = getIntent().getStringExtra("status");
        isisis = getIntent().getIntExtra("isisis", 0);
        bindViews();
        initTitle();
        initData();

    }

    private void initData() {
        types.add("周计划");
        types.add("月计划");
        types.add("自定义");
    }

    private void setListener() {
        mPlan_type.setOnClickListener(this);
        mPlan_start_time.setOnClickListener(this);
        mPlan_end_time.setOnClickListener(this);
        mPlan_message.setOnClickListener(this);
        mAdd_product.setOnClickListener(this);
    }

    private int max_cololr;

    private void initTitle() {
        max_cololr = getResources().getColor(R.color.main_color);
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);

        title.setTextColor(max_cololr);
        //title.setTextSize(20);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setVisibility(View.VISIBLE);
        if ("0".equals(status) || "1".equals(status)) {
            submit.setText("修改");
            setListener();
            title.setText("修改计划");
        } else if ("2".equals(status) || "3".equals(status) || "4".equals(status)) {
            setListener();
            title.setText("计划详情");
            showDialog();
            uploadDetail();
            submit.setVisibility(View.GONE);
            mAdd_product.setVisibility(View.GONE);
        } else {
            submit.setText("添加");
            title.setText("新增计划");
            setListener();
        }
        findViewById(R.id.btn_main_left).setOnClickListener(this);

        submit.setOnClickListener(this);
        if (isisis != 0) {
            submit.setVisibility(View.GONE);
        }

    }


    private OptionsPickerView pvOptions;
    private TimePickerView pvTime;

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.plan_start_time:

                pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        mPlan_start_time.setText(getTime(date));

                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setContentSize(18)//滚轮文字大小
                        .setTitleSize(20)//标题文字大小
                        .setTitleText("开始时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(false)//是否循环滚动
                        .setTitleColor(max_cololr)//标题文字颜色
                        .setSubmitColor(max_cololr)//确定按钮文字颜色
                        .setCancelColor(max_cololr)//取消按钮文字颜色
                        .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                        .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
                        // .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                        //.setDate(new Date())// 默认是系统时间*/
                        .setLabel("年", "月", "日", null, null, null)
                        .build();
                pvTime.show();
                break;
            case R.id.plan_end_time:

                pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        mPlan_end_time.setText(getTime(date));
                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setContentSize(18)//滚轮文字大小
                        .setTitleSize(20)//标题文字大小
                        .setTitleText("结束时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(false)//是否循环滚动
                        .setTitleColor(max_cololr)//标题文字颜色
                        .setSubmitColor(max_cololr)//确定按钮文字颜色
                        .setCancelColor(max_cololr)//取消按钮文字颜色
                        .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                        .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
                        // .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                      //  .setDate(new Date())// 默认是系统时间*/
                        .setLabel("年", "月", "日", null, null, null)
                        .build();
                pvTime.show();
                break;
            case R.id.plan_message:
                Intent intent = new Intent(this, MorePlanMessageActivity.class);
                intent.putExtra("status", status);
                ArrayList<String> message = (ArrayList<String>) messages;
                intent.putExtra("moreData", message);
                startActivityForResult(intent, PLANMESSAGE);
                break;
            case R.id.plan_type:
                pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        mPlan_type.setText(types.get(options1));
                        type = options1;
                        if (mPlan_type.getText().toString().contains(("自定义"))) {
                            mLl_end_time.setVisibility(View.VISIBLE);
                        } else {
                            mLl_end_time.setVisibility(View.GONE);
                        }
                    }
                }).build();
                pvOptions.setPicker(types);
                pvOptions.show();
                break;
            case R.id.add_product:
                List<String> content = new ArrayList<>();
                AddPlanThemeBean.ProjectEntity bean = new AddPlanThemeBean.ProjectEntity();
                bean.setContent(content);
                messageData.add(bean);
                adapter.notifyDataSetChanged();
                break;
            case R.id.submit:
                if ("".equals(mPlan_type.getText().toString().trim())) {
                    MyToast("请选择计划类型");
                    return;
                }
                if ("".equals(mPlan_info.getText().toString().trim())) {
                    MyToast("请填写关联信息");
                    return;
                }
                if ("".equals(mPlan_start_time.getText().toString().trim())) {
                    MyToast("请选择开始时间");
                    return;
                }
                if (mLl_end_time.getVisibility() == View.VISIBLE) {
                    if ("".equals(mPlan_end_time.getText().toString().trim())) {
                        MyToast("请选择结束时间");
                        return;
                    }
                }


                if (messages.size() != 0) {
                    if ("".equals(mPlan_theme.getText().toString().trim())) {
                        MyToast("请填写主题名称");
                        return;
                    }
                }
                if (messageData.size() != 0) {
                    for (int i = 0; i < messageData.size(); i++) {
                        if (messageData.get(i).getContent().size() != 0) {
                            if ("".equals(messageData.get(i).getTitle().trim())) {
                                MyToast("请填写主题名称" + (i + 1));
                                return;
                            }
                        }
                    }
                }


                showDialog();
                upLoad();

                break;
            //完成
            case R.id.plan_complete:
                showDialogv7("是否确认完成", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        upLoadCompAndTermAndDelete(1);
                    }
                });

                break;
            //终止
            case R.id.plan_termination:
                showDialogv7("是否确认终止", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        upLoadCompAndTermAndDelete(2);
                    }
                });

                break;
            //删除
            case R.id.plan_delete:
                showDialogv7("是否确认删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        upLoadCompAndTermAndDelete(3);
                    }
                });

                break;
        }
    }

    private void upLoadCompAndTermAndDelete(int type) {
        String url = "";
        switch (type) {
            case 1:
                url = Url.PLAN_COMPLETEPLAN;
                break;
            case 2:
                url = Url.PLAN_ENDPLAN;
                break;
            case 3:
                url = Url.PLAN_DELPLAN;
                break;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("planid", planid);
        XUtil.Post(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("---", result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    MyToast(info);
                    if (res.equals("1")) {
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });

    }

    private int type = 0;

    private void upLoad() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        StringBuffer json_str = new StringBuffer("{");
        //  json_str包含type   //0周计划 1月计划 2自定义计划 title关联信息  start_time end_time  project[{'title':主题,'content':内容}(多个)]
//
        json_str.append("\"type\":\"" + type + "\",");
        json_str.append("\"title\":\"" + mPlan_info.getText() + "\",");
        json_str.append("\"start_time\":\"" + mPlan_start_time.getText() + "\",");
        if (mLl_end_time.getVisibility() == View.VISIBLE)
            json_str.append("\"end_time\":\"" + mPlan_end_time.getText() + "\",");
        json_str.append("\"project\":[");
        if (!mPlan_theme.getText().toString().equals("")) {
            json_str.append("  {\n" +
                    "            \"title\":\"" + mPlan_theme.getText() + "\",\n" +
                    "                \"content\":[\n");
            for (int i = 0; i < messages.size(); i++) {
                json_str.append("\"" + messages.get(i) + "\"");
                if (i != messages.size() - 1) {
                    json_str.append(",");
                }
            }
            json_str.append("] }");
        }
        if (messageData.size() != 0) {
            json_str.append(",");
        }

        for (int i = 0; i < messageData.size(); i++) {
            if (messageData.get(i).getTitle().equals("")) {
                continue;
            }
            json_str.append(" {\n" +
                    "            \"title\":\"" + messageData.get(i).getTitle() + "\",\n" +
                    "                \"content\":[\n");
            for (int j = 0; j < messageData.get(i).getContent().size(); j++) {
                json_str.append("\"" + messageData.get(i).getContent().get(j) + "\"");
                if (j != messageData.get(i).getContent().size() - 1) {
                    json_str.append(",");
                }
            }
            json_str.append("] }");
            if (i != messageData.size() - 1) {
                json_str.append(",");
            }
        }

        json_str.append("]}");
        map.put("json_str", json_str.toString());
        Log.e("----", json_str.toString());
        String url;
        if ("0".equals(status) || "1".equals(status)) {
            url = Url.PLAN_MODIFYPLAN;
            map.put("planid", planid);
        } else {
            url = Url.PLAN_ADDPLAN;
        }

        XUtil.Post(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("---", result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    MyToast(info);
                    if (res.equals("1")) {
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    public static final int PLANMESSAGE = 934;
    public static final int PLANMESSAGEITEM = 9345;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PLANMESSAGE:
                if (resultCode == RESULT_OK) {
                    messages = (List<String>) data.getSerializableExtra("moreData");
                }
                break;
            case PLANMESSAGEITEM:
                if (resultCode == RESULT_OK) {
                    int position = data.getIntExtra("position", 0);
                    messageData.get(position).setContent((List<String>) data.getSerializableExtra("moreData"));
                    // adapter.notifyDataSetChanged();
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
